using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using RPGOnline.Rendering;

namespace RPGOnline.Controls.Map.Layers
{
    public class GridLayer : ILayer
    {
		private readonly Renderer m_renderer;
        private readonly Map m_map;
        private VertexBuffer m_grid;
	    private Color m_gridColor = Color.FromArgb(64, Color.Black);

		public GridLayer(Renderer renderer, Map map)
        {
            m_renderer = renderer;
            m_map = map;

            int verticalLines = m_map.MapSize.Width + 1;
            int horizontalLines = m_map.MapSize.Height + 1;

            m_grid = new VertexBuffer(typeof(CustomVertex.TransformedColored), 2 * verticalLines + 2 * horizontalLines, m_renderer.Device, Usage.WriteOnly, CustomVertex.TransformedColored.Format, Pool.Managed);
            var vertices = new CustomVertex.TransformedColored[2*verticalLines + 2*horizontalLines];

            int index = 0;
            for (int x = 0; x <= m_map.MapSize.Width; x++)
            {
                vertices[index].Position = new Vector4(x*m_map.TileSize.Width, 0, 0, 1.0f);
				vertices[index++].Color = m_gridColor.ToArgb();

                vertices[index].Position = new Vector4(x*m_map.TileSize.Width,
                                                       m_map.MapSize.Height*m_map.TileSize.Height, 0, 1.0f);
				vertices[index++].Color = m_gridColor.ToArgb();
            }

            for (int y = 0; y <= m_map.MapSize.Height; y++)
            {
                vertices[index].Position = new Vector4(0, y*m_map.TileSize.Height, 0, 1.0f);
				vertices[index++].Color = m_gridColor.ToArgb();

                vertices[index].Position = new Vector4(m_map.MapSize.Width*m_map.TileSize.Width, y*m_map.TileSize.Height,
                                                       0, 1.0f);
				vertices[index++].Color = m_gridColor.ToArgb();
            }

            m_grid.SetData(vertices, 0, LockFlags.None);

	        Visible = true;
        }

        public bool Visible { get; set; }

        public void Clear()
        {
        }

        public void Draw()
        {
            if (!Visible)
                return;

            int linesCount = (m_map.MapSize.Width + 1) + (m_map.MapSize.Height + 1);
	        m_renderer.DrawLineList(Matrix.Identity, m_grid, linesCount);
        }
    }
}